def minim(a,b):
if a==0:
return b
if b==0:
return a
if a<b:
return a
else:
return b
def verify(ma,i,j):
if i!=0: if ma[i-1][j] >= ma[i][j]:
return False
if j!=0: if ma[i][j-1] >= ma[i][j]:
return False
return True
def check(l,c,ma):
som=0
for i in range(l-1,-1,-1):
for j in range(c-1,-1,-1):
if ma[i][j]!=0:
if verify(ma,i,j):
som+=ma[i][j]
else:
return -1
else:
pc=0
pl=0
if i+1<l: pl = ma[i+1][j]
if j+1<c: pc = ma[i][j+1]
ma[i][j] = minim(pl,pc) - 1
if verify(ma,i,j):
som+=ma[i][j]
else:
return -1
return som
n,m = [int(i) for i in input().split()]
matrix=[]
for i in range(n): matrix.append([int(i) for i in input().split()])
var = check(n,m,matrix)
print(var)
#include <bits/stdc++.h>
#include <string>
#include <math.h>
using namespace std;
#define int long long
#define num 998244353
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--){
int n,m;
cin >> n >> m;
bool flag = 1;
int arr[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> arr[i][j];
}
}
int xr, xc, x;
for(int i = n - 2; i > 0; i--){
for(int j = m - 2; j > 0; j--){
if(!flag){
break;
}
if(arr[i][j] != 0){
continue;
}
xr = arr[i][j+1] - 1;
xc = arr[i+1][j] - 1;
x = min(xr, xc);
if(x <= arr[i-1][j] || x <= arr[i][j-1]){
flag = 0;
break;
}
else{
arr[i][j] = x;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(i == 0 && j == 0){
continue;
}
if(i == 0){
if(arr[i][j] <= arr[i][j-1]){
flag = 0;
break;
}
}
else if(j == 0){
if(arr[i][j] <= arr[i-1][j]){
flag = 0;
break;
}
}
else if(i > 0 && j > 0){
if(arr[i][j] <= arr[i][j-1] || arr[i][j] <= arr[i-1][j]){
flag = 0;
break;
}
}
}
}
if(!flag){
cout << -1 << endl;
return 0;
}
int sum = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
sum+=arr[i][j];
}
}
cout << sum << endl;
}
return 0;
}
102. Binary Tree Level Order Traversal | 96. Unique Binary Search Trees |
75. Sort Colors | 74. Search a 2D Matrix |
71. Simplify Path | 62. Unique Paths |
50. Pow(x, n) | 43. Multiply Strings |
34. Find First and Last Position of Element in Sorted Array | 33. Search in Rotated Sorted Array |
17. Letter Combinations of a Phone Number | 5. Longest Palindromic Substring |
3. Longest Substring Without Repeating Characters | 1312. Minimum Insertion Steps to Make a String Palindrome |
1092. Shortest Common Supersequence | 1044. Longest Duplicate Substring |
1032. Stream of Characters | 987. Vertical Order Traversal of a Binary Tree |
952. Largest Component Size by Common Factor | 212. Word Search II |
174. Dungeon Game | 127. Word Ladder |
123. Best Time to Buy and Sell Stock III | 85. Maximal Rectangle |
84. Largest Rectangle in Histogram | 60. Permutation Sequence |
42. Trapping Rain Water | 32. Longest Valid Parentheses |
Cutting a material | Bubble Sort |